import React, { Component } from 'react'
import ReactDOM from 'react-dom'
import Styles from './index.less'
import classnames from 'classnames'
export default class QuickLinks extends Component {
    constructor() {
        super()
        this._resizeListener = this._resizeListener.bind(this)
        this._getDomsTop = this._getDomsTop.bind(this)
        this._isNavFixed = this._isNavFixed.bind(this)
        this._synchronizeNavActive = this._synchronizeNavActive.bind(this)
        this.nav = React.createRef()
        this.state = {
            navLinksFixed: false,
            currentIndex: -1,
        }
    }
    componentDidMount() {
        // let scrollTop = document.documentElement.scrollTop || window.pageYOffset || document.body.scrollTop;
        let nav = this.nav.current
        this.navTop = nav.offsetTop
        this.navHeight = nav.offsetHeight
        this._getDomsTop()
        this._isNavFixed()
        window.addEventListener('resize', this._resizeListener)
        window.addEventListener('scroll', this._isNavFixed)
        window.addEventListener('scroll', this._synchronizeNavActive)
        console.log(this.topCache)
    }
    componentDidUpdate(prevProps, prevState) {
        // const { currentIndex } = this.state
        // if (prevState.currentIndex !== currentIndex) {
            
        // }
    }
    _isNavFixed() {
        let scrollTop = document.documentElement.scrollTop || window.pageYOffset || document.body.scrollTop;
        const { navLinksFixed } = this.state
        scrollTop > this.navTop !== navLinksFixed && this.setState({
            navLinksFixed: !navLinksFixed
        })
        // console.log(document.querySelector('.navLinks-15-Zt').offsetTop)
    }
    _synchronizeNavActive() {
        let scrollTop = document.documentElement.scrollTop || window.pageYOffset || document.body.scrollTop;
        for ( let height, index = 0 ; height = this.topCache[index++];) {
            if (height > scrollTop) {
                this.setState({currentIndex: index - 2})
                break
            }
        }
    }
    _resizeListener() {
        if (this.timer) {
            return false
        }
        let _this = this
        this.timer = setTimeout(() => {
            clearTimeout(this.timer)
            _this.timer = null
            _this._getDomsTop()
        }, 600)
    }
    _getDomsTop() {
        const { navLinks } = this.props
        const indexMatch = /\[(\S*)\]/
        const isAttrSelect = /\[(\S*?)\]/g
        const thisComp = ReactDOM.findDOMNode(this)
        let result, node, attrMatch
        this.topCache = []
        navLinks.forEach(item => { 
            node = item.node
            result = node.match(indexMatch)
            if (node.slice(0, 1) === '.') {
                if (result) {
                    this.topCache.push(thisComp.querySelectorAll(node.split('[')[0])[+result[1]].offsetTop - 2*this.navHeight)
                } else {
                    this.topCache.push(thisComp.querySelector(node).offsetTop - 2*this.navHeight)
                }
            } 
            else if (attrMatch = node.match(isAttrSelect)) {
                if (attrMatch.length > 1) {
                    this.topCache.push(thisComp.querySelectorAll(attrMatch[0])[+attrMatch[1].match(indexMatch)[1]].offsetTop - 2*this.navHeight)
                } else {
                    this.topCache.push(thisComp.querySelector(attrMatch[0]).offsetTop - 2*this.navHeight)
                }
            }
        })
        this.topCache.push(thisComp.offsetTop + thisComp.offsetHeight)
    }
    componentWillUnmount() {
        window.removeEventListener('resize', this._resizeListener)
        // window.removeEventListener('scroll', this._resizeListener)
        window.removeEventListener('scroll', this._isNavFixed)
        window.removeEventListener('scroll', this._synchronizeNavActive)
    }
    toTheTop(index) {
        this.setState({
            currentIndex: index
        })
        window.scrollTo(0, this.topCache[index])
    }
    render() {
        const { children, navLinks } = this.props
        const { navLinksFixed, currentIndex } = this.state
        return (
        <div className={classnames(Styles.quickLinks)}>
            <div className={classnames(Styles.navLinks, {[Styles.navLinksFixed]: navLinksFixed})} ref={this.nav}>
                <div className={Styles.navLinksContainer}>
                    {navLinks.map((item, index) => (<div onClick={this.toTheTop.bind(this, index)} key={item.node} className={Styles.navLinksItem}>
                        <span className={classnames(Styles.navLinksItemText, {[Styles.navLinksItemActive]: index === currentIndex})}>{item.name}</span>
                    </div>))}
                </div>
            </div>
            { children }
        </div>
        )
    }
}